//
//  XTMatchViewController.m
//  BeautifulHome
//
//  Created by dlios on 15-5-13.
//  Copyright (c) 2015年 ACE. All rights reserved.
//

#import "XTMatchViewController.h"
#import "XTMatchTableViewCell.h"
#import "XTMatchCollectionViewCell.h"
#import "XTGoodsViewController.h"
#import "XTPIcDetailViewController.h"
#import "NetworkHandle.h"
#import "XTMatch.h"
#import "XTGoods.h"
#import "UIImageView+WebCache.h"
#import "MXPullDownMenu.h"
#import "MJRefresh.h"
#import "XTMyLoginViewController.h"
#import "AppDelegate.h"

@interface XTBaseViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, MXPullDownMenuDelegate>
@property (retain, nonatomic) NSString *houseStyle;
@property (retain, nonatomic) NSString *typeShow;
@end

@implementation XTMatchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = NO;
    self.isUpLoading = NO;
    self.navigationController.navigationBar.translucent = NO;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"我的" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    self.myArr = [NSMutableArray array];
    self.meArr = [NSMutableArray array];
    self.mySeg = [[UISegmentedControl alloc] initWithItems:@[@"搭配", @"单品"]];
    _mySeg.frame = CGRectMake(120, 30, 135, 30);
    self.mySeg.selectedSegmentIndex = 0;
    self.navigationItem.titleView = self.mySeg;
    NSLog(@"%@", self.navigationController);
    
    [_mySeg release];
    [_mySeg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    
//    self.danpinView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
//    
//    [self.view addSubview:_danpinView];
    [self createdCollectionView];

//    [self.danpinView release];
//    self.dapeiView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
//    _danpinView.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:_dapeiView];

//    [self.danpinView release];
//    self.dapeiView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
//    _danpinView.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:_dapeiView];

    [self createdTableView];
//    [self.dapeiView release];
    [self addHeader];
    [self addFooter];
//    [self addNewHeader];
    [self addNewFooter];
    
    self.myCount = 0;
    //[self creatNotificationCenter];
}
//- (void)rightButtonAction
//{
//    self.myCount = self.myCount + 1;
//    if (self.myCount == 1) {
//        NSArray *testArray;
//        testArray = @[ @[ @"风格", @"全部风格", @"现代", @"简约", @"韩式" , @"地中海" , @"欧式",@"中式",@"日式",@"新古典",@"宜家",@"田园",@"混搭",@"清新",@"小资" ], @[@"户型", @"全部户型",@"一居",@"两居",@"三居",@"四居",@"小户型",@"大户型",@"别墅",@"复式",@"公寓",@"跃层",@"LOFT",@"阁楼"]];
//        MXPullDownMenu *menu = [[MXPullDownMenu alloc] initWithArray:testArray selectedColor:[UIColor blackColor]];
//        menu.delegate = self;
//        menu.tag = 10001;
//        menu.frame = CGRectMake(0, 0, self.view.frame.size.width , menu.frame.size.height);
//        [self.view addSubview:menu];
//    } else if (self.myCount % 2 == 0) {
//        MXPullDownMenu *menu = (MXPullDownMenu *)[self.view viewWithTag:10001];
//        menu.hidden = YES;
//    }
//    else if (!(self.myCount % 2 == 0 && self.myCount == 1)){
//        MXPullDownMenu *menu = (MXPullDownMenu *)[self.view viewWithTag:10001];
//        
//        menu.hidden = NO;
//    }
//    
//}
- (void)leftButtonAction
{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (tempAppDelegate.LeftSlideVC.closed)
    {
        [tempAppDelegate.LeftSlideVC openLeftView];
    }
    else
    {
        [tempAppDelegate.LeftSlideVC closeLeftView];
    }
}
//- (void)PullDownMenu:(MXPullDownMenu *)pullDownMenu didSelectRowAtColumn:(NSInteger)column row:(NSInteger)row
//{
////
////    MXPullDownMenu *menu = (MXPullDownMenu *)[self.view viewWithTag:10001];
////    menu.hidden = YES;
//    NSLog(@"%ld, %ld", column, row);
//    
//    
//}
- (void)segAction:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        self.myTableView.hidden = NO;
        self.myCollectionView.hidden = YES;
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
        [self addHeader];
        
    }
    if (seg.selectedSegmentIndex == 1) {
//        self.myCount = self.myCount + 1;
        self.myTableView.hidden = YES;
        self.myCollectionView.hidden = NO;
//        MXPullDownMenu *menu = (MXPullDownMenu *)[self.view viewWithTag:10001];
//        menu.hidden = YES;
//        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] init] autorelease];
        [self addNewHeader];
    }

}
- (void)createdTableView
{
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_myTableView];
    [_myTableView release];
}
- (void)createdCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width / 2 - 10, self.view.frame.size.height / 2 - 50);
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) collectionViewLayout:flowLayout];
    _myCollectionView.dataSource = self;
    _myCollectionView.delegate = self;
    _myCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myCollectionView];
    [_myCollectionView release];
    [_myCollectionView registerClass:[XTMatchCollectionViewCell class] forCellWithReuseIdentifier:@"my"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _myArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"str";
    XTMatchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[XTMatchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    XTMatch *match = _myArr[indexPath.row];
    NSString *url = [NSString stringWithFormat:@"http://gooju.cn/dimages/%@_0_w640_h0_m0.jpg",match.picId];
    [cell.background sd_setImageWithURL:[NSURL URLWithString:url]placeholderImage:[UIImage imageNamed:@"3-1"]];
    cell.idNameLabel.text = [match.user objectForKey:@"userName"];
    NSString *headUrl = [[match.user objectForKey:@"userImage"] objectForKey:@"small"];
    [cell.headPortrait sd_setImageWithURL:[NSURL URLWithString:headUrl]placeholderImage:[UIImage imageNamed:@"my.jpg"]];
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 280;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XTPIcDetailViewController *picDetailVC = [[[XTPIcDetailViewController alloc] init] autorelease];
    XTMatch *match = [[XTMatch alloc] init];
    match = _myArr[indexPath.row];
    picDetailVC.match = match;
    [self.navigationController pushViewController:picDetailVC animated:YES];
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.meArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    XTMatchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"my" forIndexPath:indexPath];
    XTGoods *goods = [[XTGoods alloc] init];
    goods = self.meArr[indexPath.row];
    cell.myLabel.text = goods.title;
    NSString *url = [goods.images objectAtIndex:0];
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:url]placeholderImage:[UIImage imageNamed:@"3-1"]];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    XTGoodsViewController *goodsVC = [[[XTGoodsViewController alloc] init] autorelease];
    XTGoods *goods = _meArr[indexPath.row];
    goodsVC.imageUrl = goods.images;
    goodsVC.myTitle = goods.title;
    goodsVC.address = goods.addresses;
    goodsVC.prices = goods.price;
    goodsVC.myGoods = goods;
    [self.navigationController pushViewController:goodsVC animated:YES];
}
- (void)getData:(NSInteger)start
{
    NSString *string = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/photo/flownew?start=%ld&count=5&user=(null)&cate=101&style=205&color=306", start];
    [NetworkHandle getDataWithURL:string completion:^(id result) {
        self.start = [[result objectForKey:@"start"] integerValue] + 5;
        NSLog(@"~~~~~%ld", self.start);
        NSLog(@"^^^^^^%@", result);
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.myArr removeAllObjects];
        }
        NSArray *arr = [result objectForKey:@"photos"] ;
        
        for (NSDictionary *dic in arr) {
            XTMatch *mathch = [[XTMatch alloc] initWithDic:dic];
            [mathch setPicId:[dic objectForKey:@"id"]];
            [self.myArr addObject:mathch];
            [mathch release];
        }
        [self.myTableView footerEndRefreshing];//结束底部刷新效果
        [self.myTableView headerEndRefreshing];//结束头部刷新效果
        [self.myTableView reloadData];
        
    }];
}
- (void)getNewData:(NSInteger)start
{
    NSString *string = [NSString
                        stringWithFormat:@"http://api.guju.com.cn/v2/product/productFlowNew?start=%ld&count=10&user=(null)&cate=0&style=0&color=0", start];
    [NetworkHandle getDataWithURL:string completion:^(id result) {
        self.start = [[result objectForKey:@"start"] integerValue] + 10;
        NSLog(@"~~~~~%ld", self.start);
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.meArr removeAllObjects];
        }
        NSArray *arr = [result objectForKey:@"products"] ;
        
        for (NSDictionary *dic in arr) {
            XTGoods *goods = [[XTGoods alloc] initWithDic:dic];
            [_meArr addObject:goods];
            [goods release];
        }
        NSLog(@"~~~___%@", _meArr);
        [self.myCollectionView footerEndRefreshing];//结束底部刷新效果
        [self.myCollectionView headerEndRefreshing];//结束头部刷新效果
        [self.myCollectionView reloadData];
    }];
}
#pragma mark --下拉刷新
- (void)addHeader
{
    __block XTMatchViewController *mVC = self;
    // 添加下拉刷新头部控件
    [self.myTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        mVC.isUpLoading = NO;//标记为下拉操作
        [mVC getData:0];//重新请求数据
        
    }];
    
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTableView headerBeginRefreshing];
    
}
- (void)addNewHeader
{
    __block XTMatchViewController *mVC = self;
    // 添加下拉刷新头部控件
    [self.myCollectionView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        mVC.isUpLoading = NO;//标记为下拉操作
        [mVC getNewData:0];//重新请求数据
        
    }];
    [self.myCollectionView headerBeginRefreshing];
}
#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block XTMatchViewController *mVC = self;
    
    // 添加上拉刷新尾部控件
    [self.myTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        mVC.isUpLoading = YES;//标记为上拉操作
        [mVC getData:mVC.start];//请求更多数据
        
    }];
    
    
}
- (void)addNewFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block XTMatchViewController *mVC = self;
    
    // 添加上拉刷新尾部控件
    [self.myCollectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        mVC.isUpLoading = YES;//标记为上拉操作
        [mVC getNewData:mVC.start];//请求更多数据
        
    }];
}
- (void)creatNotificationCenter
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changeColor:) name:@"color" object:nil];
}
- (void)changeColor:(NSNotification *)noti
{
    self.navigationController.navigationBar.translucent = NO;
    self.backgroundColor = noti.object;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:self.backgroundColor] forBarMetrics:UIBarMetricsDefault];
}
//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
////    NSLog(@"viewWillDisappear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
//}
//
//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
////    NSLog(@"viewWillAppear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:YES];
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
